<!--
 * @Author: zhuxiaoyi
 * @Date: 2024-01-09 10:50:36
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2024-04-25 11:27:42
 * @Description: 
-->
<template>
    <el-row>
        <el-col :span="24" style="padding: 20px;">
            <el-row>
                <el-col :span="24">
                    <el-card class="preview-card">
                        <template #header>
                            <div class="preview-card-header">
                                <el-page-header @back="goBack">
                                    <template #content>
                                        <span class="text-large font-600 mr-3"> 图层编辑 </span>
                                    </template>
                                </el-page-header>
                                <el-button-group style="margin-left:10px">
                                    <el-button type="primary" :icon="FolderChecked">保存</el-button>
                                </el-button-group>
                            </div>
                        </template>
                        <el-row>
                            <el-col :span="24" style="display: flex;justify-content:flex-end;position: relative;">
                                <div style="position: absolute;z-index: 100;right: 10px;top: 10px;">
                                    <el-popover :width="300" placement="bottom-end" class="map-popover"
                                        :popper-style="{ padding: 0 }" :visible="popoverVisible">
                                        <template #reference>
                                            <el-avatar shape="square" :size="30"
                                                style="background-color: rgba(240, 248, 255, 0);cursor: pointer;"
                                                @click="popoverVisible = !popoverVisible" :src="mapIcon" />
                                        </template>
                                        <template #default>
                                            <el-card class="base-layer-card" size="small">
                                                <template #header>
                                                    <div class="base-layer-header">
                                                        <span>选择底图</span>
                                                        <el-button link class="button" @click="popoverVisible = false"
                                                            :icon="Close"></el-button>
                                                    </div>
                                                </template>
                                                <div class="base-layer-container">
                                                    <el-card v-for="layer in baseLayers" :key="layer.type"
                                                        :body-style="{ padding: '0px' }" style="width:74px;cursor: pointer;"
                                                        class="img-card" @click="baseImageClickHandler(layer)">
                                                        <el-image style="width: 74px; height: 54px" :src="layer.img"
                                                            :fit="'fill'" />
                                                        <div style="padding: 5px">
                                                            <span>{{ layer.name }}</span>
                                                        </div>
                                                    </el-card>
                                                </div>
                                                <template #footer>
                                                    <el-row>
                                                        <el-col style="display: flex; justify-content:space-between">
                                                            矢量图层
                                                            <el-switch v-model="resultLayerVisible"
                                                                @change="switchChangeHandler" />
                                                        </el-col>
                                                    </el-row>
                                                </template>
                                            </el-card>
                                        </template>
                                    </el-popover>
                                </div>
                            </el-col>
                        </el-row>
                        <div id="map-container" :style="`height:${view.height - 230}px`" @click="popoverVisible = false"></div>
                    </el-card>
                </el-col>
            </el-row>
        </el-col>
    </el-row>
</template>
<script setup lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted, watch } from "vue";
import { Close } from "@element-plus/icons-vue";
import { useRouter, useRoute } from "vue-router";
import { Map, View } from 'ol'
import { Style, Fill, Stroke } from 'ol/style'
import { Tile as TileLayer } from 'ol/layer'
import { get } from 'ol/proj';
import { getWidth, getTopLeft } from 'ol/extent'
import { WMTS, TileWMS, OSM } from 'ol/source'
import { WFS, GeoJSON } from 'ol/format';
import WMTSTileGrid from 'ol/tilegrid/WMTS'
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import Select from 'ol/interaction/Select';
import { singleClick } from 'ol/events/condition';
import Modify from 'ol/interaction/Modify';
import 'ol/ol.css'; // 导入 OpenLayers 样式文件
import baseImg1 from '@/assets/img/vec.jpg'
import baseImg2 from '@/assets/img/img.jpg'
import baseImg3 from '@/assets/img/ter.jpg'
import mapIcon from '@/assets/img/map2.png'
import { FolderChecked } from '@element-plus/icons-vue'
var view = reactive({
    height: window.innerHeight,
});
const resultLayerVisible = ref(true)
const popoverVisible = ref(false)
const router = useRouter()
const projection = get("EPSG:4326");
const projectionExtent = projection.getExtent();
const size = getWidth(projectionExtent) / 256;
const resolutions = [];
const baseLayers = [
    {
        type: "vecLayer",
        name: "矢量底图",
        img: baseImg1
    },
    {
        type: 'imgLayer',
        name: "影像底图",
        img: baseImg2
    },
    {
        type: 'terLayer',
        name: "地形晕渲",
        img: baseImg3
    }
]
let map;
for (let z = 2; z < 19; ++z) {
    resolutions[z] = size / Math.pow(2, z);
}
onMounted(() => {
    initMap()
});
// 切换底图函数

const baseImageClickHandler = function (layer) {
    switchBaseLayer(layer.type)
}
const switchBaseLayer = (layerType) => {
    if (!map) return; // 如果地图对象不存在，则返回
    map.getLayers().forEach(layer => {
        if (layer.values_.name == layerType || layer.values_.name == 'cvaLayer' || layer.values_.name == 'resultLayer') {
            layer.setVisible(true)
        } else {
            layer.setVisible(false)
        }
    });
}
const switchChangeHandler = function () {
    changeLayerVisible('resultLayer', resultLayerVisible.value)
}
const changeLayerVisible = function (layerName, visible) {
    map && map.getLayers().forEach(layer => {
        if (layer.values_.name == layerName) {
            layer.setVisible(visible)
        }
    });
}

const initMap = function () {
    const TIANDI_KEY = 'eec7fae87888db2dc4c30c0c458fb66b'
    // const center = ref([116.41124529391394, 39.953530444730816]);
    const center = ref([103.160298, 26.253992]);
    // c: 经纬度投影 w: 球面墨卡托投影
    const matrixSet = 'c'

    const wfsSource = new VectorSource({
        format: new GeoJSON(),
        url: function (extent) {
            return (
                'http://localhost:8055/geoserver/result/ows?service=WFS&' +
                'version=1.0.0&request=GetFeature&typeName=result:aaa1&' +
                'outputFormat=application/json&srsname=EPSG:4326&' +
                'bbox=' + extent.join(',') + ',EPSG:3857'
            );
        },
    });

    let vectorLayer = new VectorLayer({
        source: wfsSource,
        style: function (feature) {
            var classValue = feature.get('class');
            var color = '';
            if (classValue == '1') {
                // color = '#68A7C4';
                color = '#ABC6EF';
            } else if (classValue == '2') {
                // color = '#EEEEEE';
                color = 'rgba(255, 255, 255,0)';
            } else {
                color = 'red'; // 默认颜色
            }
            return new Style({
                fill: new Fill({
                    color: color
                }),
                stroke: new Stroke({
                    color: '#7ABCDE',
                    width: 1
                })
            });
        }
    });
    vectorLayer.set('name', "resultLayer")

    const terLayer = new TileLayer({
        source: new WMTS({
            url: `http://t{0-6}.tianditu.com/${'ter'}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
            layer: 'ter',
            matrixSet: matrixSet,
            style: "default",
            crossOrigin: 'anonymous', // 解决跨域问题 如无该需求可不添加
            format: "tiles",
            wrapX: true,
            tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                //resolutions: res.slice(0, 15),
                resolutions: resolutions,
                matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
            })
        })
    })
    terLayer.set('name', "terLayer")

    const imgLayer = new TileLayer({
        source: new WMTS({
            url: `http://t{0-6}.tianditu.com/${'img'}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
            layer: 'img',
            matrixSet: matrixSet,
            style: "default",
            crossOrigin: 'anonymous', // 解决跨域问题 如无该需求可不添加
            format: "tiles",
            wrapX: true,
            tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                //resolutions: res.slice(0, 15),
                resolutions: resolutions,
                matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
            })
        })
    })
    imgLayer.set('name', "imgLayer")

    const vecLayer = new TileLayer({
        source: new WMTS({
            url: `http://t{0-6}.tianditu.com/${'vec'}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
            layer: 'vec',
            matrixSet: matrixSet,
            style: "default",
            crossOrigin: 'anonymous', // 解决跨域问题 如无该需求可不添加
            format: "tiles",
            wrapX: true,
            tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                //resolutions: res.slice(0, 15),
                resolutions: resolutions,
                matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
            })
        })
    })

    vecLayer.set('name', "vecLayer")

    const cvaLayer = new TileLayer({
        source: new WMTS({
            url: `http://t{0-6}.tianditu.com/${'cva'}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
            layer: 'cva',
            matrixSet: matrixSet,
            style: "default",
            crossOrigin: 'anonymous', // 解决跨域问题 如无该需求可不添加
            format: "tiles",
            wrapX: true,
            tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                resolutions: resolutions,
                matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
            })
        })
    })
    cvaLayer.set('name', "cvaLayer")
    /* const resultLayer = new TileLayer({
        source: new TileWMS({
            url: 'http://localhost:8055/geoserver/result/wms',
            params: {
                LAYERS: "result:test11111",
                STYLES: "",
                VERSION: "1.1.1",
                tiled: true
            },
            serverType: 'geoserver'
        })
    }) */

    map = new Map({
        target: 'map-container',
        layers: [
            terLayer,
            // 底图
            imgLayer,
            vecLayer,
            // 标注
            cvaLayer,
            vectorLayer
        ],
        view: new View({
            center: center.value,
            projection: projection,
            zoom: 13,
            maxZoom: 17,
            minZoom: 1
        })
    })

    let selectInteraction = new Select({
        condition: singleClick,
        style: function (feature) {
            // 自定义选中要素的样式，保留填充色
            var classValue = feature.get('class');
            var color = '';
            if (classValue == '1') {
                color = '#67c23a';
            } else if (classValue == '2') {
                color = '#CEEAD6';
            } else {
                color = 'rgba(255, 255, 255,0.1)'; // 默认颜色
            }
            return new Style({
                fill: new Fill({
                    color: color // 自定义填充色
                }),
                stroke: new Stroke({
                    color: '#529b2e', // 自定义边框颜色
                    width: 2 // 自定义边框宽度
                })
            });
        }
    });

    map.addInteraction(selectInteraction);

    let modifyInteraction = new Modify({
        features: selectInteraction.getFeatures()
    });

    map.addInteraction(modifyInteraction);

    selectInteraction.on('select', function (event) {
        if (event.selected.length > 0) {
            const selectedFeature = event.selected[0];
            // 处理选择的要素属性
            console.log(selectedFeature.getProperties());
        }
    });

}

const goBack = function () {
    router.push('/index/general/executeManage/executeList')
}
var view = reactive({
    height: window.innerHeight,
});
</script>
<style lang="scss" scoped>
#map-container {
    width: 100%;
    height: 600px;
    cursor: pointer;
}



.preview-card-header {
    display: flex;
    justify-content: space-between;
}

.base-layer-card {

    .base-layer-header {
        display: flex;
        justify-content: space-between;

    }

    .base-layer-container {
        display: flex;
        justify-content: space-between;
    }

    .img-card {
        border: 2px solid hsla(210, 96%, 54%, 0);

        &:hover {
            border: 2px solid #1989fa;
        }
    }
}
</style>
<style lang="scss">
.map-popover {
    padding: 0;
}

.preview-card {
    .el-card__header {
        padding: 10px !important;
    }

    .el-card__body {
        padding: 0;
    }
}

.base-layer-card {
    .el-card__header {
        padding: 5px !important;
    }

    .el-card__body {
        padding: 15px;
    }

    .el-card__footer {
        padding: 5px !important;
    }
}
</style>